<?php

// 定义函数处理目录映射
use GuzzleHttp\Client;
use Hyperf\Guzzle\HandlerStackFactory;

if (! function_exists('registerCoreMap')) {
    function registerCoreMap(string $basePath, string $namespacePrefix = 'Plugins\\Demo'): array {
        $dependencies = [];
        $layers = ['Action', 'Logic', 'Service']; // 添加控制器、逻辑、服务目录

        foreach ($layers as $layer) {
            $layerPath = $basePath . '/' . $layer;
            if (! is_dir($layerPath)) {
                continue;
            }

            $implementationPath = $layerPath; // 实现类目录
            $interfacePath = $layerPath . '/Interface'; // 接口目录

            $implementations = readFileName($implementationPath);

            $interfaces = readFileName($interfacePath);
            // 循环匹配实现类和接口
            foreach ($implementations as $impl) {
                //过滤空的
                if (empty($impl)){
                    continue;
                }
                $interfaceName = 'I' . $impl; // 假设接口名称与实现类名称相同，但以Interface结尾
                if (in_array($interfaceName, $interfaces)) {
                    $dependencies[$namespacePrefix . "\\" . $layer . '\\Interface\\' . $interfaceName] = $namespacePrefix . "\\" . $layer . "\\" . $impl;
                }
            }
        }
        return $dependencies;
    }
}
// 定义读取文件名的函数
if (! function_exists('readFileName')) {
    function readFileName(string $path): array {
        $files = scandir($path);
        $fileNames = [];

        foreach ($files as $file) {
            // 确保是 PHP 文件
            if (is_file($path . '/' . $file) && pathinfo($file, PATHINFO_EXTENSION) === 'php') {
                $fileNames[] = pathinfo($file, PATHINFO_FILENAME);
            }
        }

        return $fileNames;
    }
}
//post请求方法
if (! function_exists('curlPost')) {
    /**
     * @throws Exception
     */
    function curlPost($url, $data = [], $header = [])
    {
        $factory = new HandlerStackFactory();
        $stack = $factory->create();

        $client = \Hyperf\Support\make(Client::class, [
            'config' => [
                'handler' => $stack,
            ],
        ]);
        try {
            return $client->post($url, [
                'form_params' => $data,
                'headers' => $header,
            ]);
        } catch (\GuzzleHttp\Exception\GuzzleException $e) {
            throw new \Exception($e->getMessage());
        }
    }
}
//get请求方法
if (! function_exists('curlGet')) {
    /**
     * @throws Exception
     */
    function curlGet($url, $data = [], $header = [])
    {
        $factory = new HandlerStackFactory();
        $stack = $factory->create();

        $client = \Hyperf\Support\make(Client::class, [
            'config' => [
                'handler' => $stack,
            ],
        ]);
        try {
            return $client->get($url, [
                'query' => $data,
                'headers' => $header,
            ]);
        } catch (\GuzzleHttp\Exception\GuzzleException $e) {
            throw new \Exception($e->getMessage());
        }
    }
}

// 用户密码加密方式，双重md5加盐
if (! function_exists('passwordMd5')) {
    function passwordMd5(string $password): array {
        // 生成六位随机盐
        $salt = substr(md5(uniqid(mt_rand(), true)), 0, 6);
        $hash = md5(md5($password).$salt);
        return [
            'password' => $hash,
            'salt' => $salt,
        ];
    }
}

// 用户密码验证
if (! function_exists('passwordMd5Verify')) {
    function passwordMd5Verify(string $password, string $hash, string $salt): bool {
        if($hash == md5(md5($password).$salt)){
            return true;
        }else{
            return false;
        }
    }
}

//生成不重复的数字大小写字母组成的字符串，可以定义长度
if (! function_exists('randomStr')) {
    function randomStr(int $length = 6): string {
        $str = '';
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol) - 1;

        for ($i = 0; $i < $length; $i++) {
            $str.= $strPol[rand(0, $max)];
        }
        return $str;
    }
}

if (! function_exists('user')) {
    /**
     * 获取后台用户信息
     *
     * @param string $field 字段名称
     * @return array|string 用户信息|用户字段信息
     */
    function user(?string $field = null): array|string
    {
        $request = \Hyperf\Context\Context::get(\Psr\Http\Message\ServerRequestInterface::class);
        $resData = $request->getAttribute('user');

        if (! $resData) {
            return [];
        }

        $userData = $request->getAttributes();
        foreach ($userData as $key => $val) {
            if (strpos($key, '_user_') === 0) {
                $resData[substr($key, 6)] = $val;
            }
        }
        $field && $resData = $resData[$field];

        return $resData;
    }
}

if (! function_exists('responseDataFormat')) {
    function responseDataFormat($code, string $message = '', array $data = []): array
    {
        return [
            'code' => $code,
            'msg'  => $message,
            'data' => $data,
        ];
    }
}